<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

  <title>Horizontal Playground</title>
  <link href="../button.css" rel="stylesheet" type="text/css">
  <link href="../font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <script src="../local_blockly_compressed_horizontal.js"></script>

  <script src="../msg/messages.js"></script>
  <script src="../blocks_common/math.js"></script>
  <script src="../blocks_common/text.js"></script>
  <script src="../blocks_horizontal/control.js"></script>
  <script src="../blocks_horizontal/event.js"></script>
  <script src="../blocks_horizontal/wedo.js"></script>
  <script src="../blocks_horizontal/default_toolbox.js"></script>

  <script src="../jquery-3.5.0.min.js"></script>
  <script type="text/javascript" src="../jquery.json2xml.js"></script>
  <script type="text/javascript" src="../jquery.xml2json.js"></script>

  <script>
    var $xml = jQuery.noConflict();
    var code_finish = true;
    var code_running = false;
    var forever_id;
    function get_scratch_json() {
      var _code = Blockly.Xml.workspaceToDom(workspace);
      return $xml.xml2json(_code);
    }

    function run_code(c) {
      if (c["@type"] == "event_whenflagclicked") {
        console.log("green flag")
        code_running = true;
      }
      else if (c["@type"] == "wedo_setcolor") {
        console.log(c.value.shadow.field.text)
      }
      else if (c["@type"] == "control_wait") {
        console.log("delay " + c.value.shadow.field.text + "s")
        if ('next' in c) {
          setTimeout(
            () => run_code(c.next.block),
            parseInt(c.value.shadow.field.text) * 1000
          )
        }
        else
        {
          setTimeout(
            () => code_finish = true,
            parseInt(c.value.shadow.field.text) * 1000
          )
        }
        return
      }
      else if (c["@type"] == "control_forever") {
        console.log("start infinite loop")
      }

      if ('next' in c) {
          return run_code(c.next.block);
      }
      else if (c["@type"] == "control_forever") {
        if ('statement' in c) {
          forever_id = setInterval(() => {
            if (code_running) {
              if (code_finish) {
                code_finish = false;
                run_code(c.statement.block);
              }
            }
          }
            , 10)
        }
      }
      else {
        code_finish = true;
        return;
      }
    }

    function parse_code() {
      if(code_running)
      {
        code_running = false;
        clearInterval(forever_id);
      }
      console.log('start parsing ...');
      var code = get_scratch_json();
      var green_flag;
      if ('block' in code) {
        var i;
        if (code.block.length == undefined) {
          // 仅有一个block组存在
          if (code.block["@type"] == "event_whenflagclicked") {
            run_code(code.block);
          }
        }
        else {
          // 多个离散的block在工作区的情况
          for (i = 0; i < code.block.length; i++) {
            if (code.block[i]["@type"] == "event_whenflagclicked") {
              green_flag = i;
              break;
            }
          }
          if (i < code.block.length) {
            run_code(code.block[green_flag]);
          }
          else {
            console.log("no start block!");
          }
        }
      }
      else {
        console.log('no blocks!')
      }
    }
  </script>

  <script>
    'use strict';
    var workspace = null;

    function start() {

      workspace = Blockly.inject('blocklyDiv', {
        comments: true,
        disable: false,
        collapse: false,
        media: '../media/',
        readOnly: false,
        rtl: false,
        scrollbars: true,
        toolbox: document.getElementById('toolbox'),
        trashcan: true,
        horizontalLayout: true,
        toolboxPosition: 'end',
        sounds: null,
        grid: {
          spacing: 16,
          length: 1,
          colour: '#2C344A',
          snap: false
        },
        zoom: {
          controls: true,
          wheel: true,
          startScale: 1.0,
          maxScale: 4,
          minScale: 0.25,
          scaleSpeed: 1.1
        },
        colours: {
          fieldShadow: 'rgba(255, 255, 255, 0.3)',
          dragShadowOpacity: 0.6
        }
      });

      workspace.addChangeListener(block_change_handler);

      function block_change_handler(e) {

        // scratch默认方法有个bug，不能自动更新前端显示的数字
        function html_bug_fix(id, value) {
          var b = workspace.getBlockById(id);
          var b_text = b.inputList[0].fieldRow[0].textElement_
          b_text.innerHTML = value
        }

        if ("name" in e) {
          if (e.name == "NUM") {
            html_bug_fix(e.blockId, e.newValue);
          }
        }
      }

    }

  </script>

  <style>
    html,
    body {
      height: 80%;
    }

    body {
      background-color: #fff;
      font-family: sans-serif;
    }

    #blocklyDiv {
      height: 100%;
      width: 100%;
    }
  </style>
</head>

<body onload="start()">
  <xml id="toolbox" style="display: none">
    <block type="event_whenflagclicked"></block>

    <block type="control_forever"></block>

    <block type="control_wait">
      <value name="DURATION">
        <shadow type="math_number">
          <field name="NUM">1</field>
        </shadow>
      </value>
    </block>

    <block type="wedo_setcolor">
      <value name="CHOICE">
        <shadow type="dropdown_wedo_setcolor">
          <field name="CHOICE">mystery</field>
        </shadow>
      </value>
    </block>

  </xml>
  <div id="blocklyDiv"></div>
  <br/>
  <br/>
  <i class="logo" onclick="parse_code()"><i class="fa fa-flag"></i></i>
</body>

</html>